#!/usr/bin/env python3
#coding:utf-8

__author__ = 'xmxoxo<xmxoxo@qq.com>'

import traceback
import logging

from faces_lib import *
from PyQt5.QtCore import pyqtSlot, QCoreApplication, QEvent
from PyQt5.QtWidgets import QMainWindow, QApplication, QGraphicsScene, QGraphicsPixmapItem, QFileDialog, QMessageBox
from PyQt5.QtGui import QImage, QPixmap, QTextCursor, QIcon

'''
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
'''
from winform.ui_face_search import Ui_MainWindow

gblVersion = '0.2.0'

class Viewer(QMainWindow, Ui_MainWindow):
    """
    Class documentation goes here.
    """
    def __init__(self, parent=None):
        self.title = '客户端'
        super(Viewer, self).__init__(parent)
        self.setupUi(self)

        # 设置图标
        icon = QIcon("icon.ico")
        self.setWindowIcon(icon)

        self.statusBar().showMessage('准备就绪...')



    def showImage(self, fileName):
        imgShow = QPixmap()
        imgShow.load(fileName)
        imgShowItem = QGraphicsPixmapItem()
        imgShowItem.setPixmap(QPixmap(imgShow))
        #imgShowItem.setPixmap(QPixmap(self.imgShow).scaled(270, 270))    #自己设定尺寸
        
        self.graphicsView_source.scene_img = QGraphicsScene()
        self.graphicsView_source.scene_img.addItem(imgShowItem)
        self.graphicsView_source.setScene(self.graphicsView_source.scene_img)
        self.graphicsView_source.fitInView(QGraphicsPixmapItem(QPixmap(self.imgShow)))    #图像自适应大小

    def showImage1(self, fname):
        x, y = 281, 281
        #frame = QImage(fname)

        image = Image.open(fname, 'r')
        required_size = (270, 270)
        image = image.resize(required_size)

        #img = cv2.cvtColor(np.asarray(image), cv2.COLOR_BGR2RGB) #COLOR_RGB2BGR
        img = np.asarray(image)
        #x, y = list(img.shape)[::-1]
        x = img.shape[1]                                        #获取图像大小
        y = img.shape[0]

        frame = QImage(img, x, y, QImage.Format_RGB888)
        pix = QPixmap.fromImage(frame)
        item = QGraphicsPixmapItem(pix)
        scene = QGraphicsScene()
        scene.addItem(item)
        self.graphicsView_source.setScene(scene)

    # 把图像显示在控件里
    def showimg (self, fname):
        try:
            #if fname is None: return
            image = Image.open(fname, 'r')
            print(image)
            #face_image = np.asarray(image, 'float32')
            #data_img = Image.fromarray(image)
            #data_img = data_img.convert("RGBA")
            data_img = np.asarray(image)
            print(data_img.shape)

            img = cv2.cvtColor(data_img, cv2.COLOR_BGR2RGB)              #转换图像通道
            x = img.shape[1]                                        #获取图像大小
            y = img.shape[0]
            self.zoomscale = 1                                        #图片放缩尺度
            frame = QImage(img, x, y, QImage.Format_RGB888)
            pix = QPixmap.fromImage(frame)
            self.item = QGraphicsPixmapItem(pix)                      #创建像素图元
            self.item.setScale(self.zoomscale)
            self.scene = QGraphicsScene()                             #创建场景
            self.scene.addItem(self.item)
            self.graphicsView_source.setScene(self.scene)                        #将场景添加至视图
        except Exception as e:
            print(e)
            pass

    # 拖放事件
    @pyqtSlot()
    def on_graphicsView_source_droped(self):
        print('droped...')
        #print('double_click...')

    # 事件
    @pyqtSlot()
    def on_graphicsView_source_mouseclicked(self):
        #print('Droping...')
        print('click...')

    @pyqtSlot()
    def on_face_s_clicked(self):
        #print('Droping...')
        print('click1...')

    def dragEnterEvent(self, event):
        print(event)
        '''
        if event.mimeData().hasText():
            event.accept()
        else:
            event.ignore()
        '''
        event.acceptProposedAction()

    def dropEvent(self, event):
        print('Droping...')
        print(event)
        text = event.mimeData().text()
        print('text:', text)
        fname = text.replace('file:///', '')
        #self.showimg(fname)
        self.showImage(fname)

def main():
    app = QApplication(sys.argv)
    w = Viewer()
    w.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    pass
    #################################################################################################
    # 指定日志
    logging.basicConfig(level = logging.DEBUG,
                format='[%(asctime)s] %(filename)s [line:%(lineno)d] %(levelname)s %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename= os.path.join('./', 'client.log'),
                filemode='a'
                )
    #################################################################################################
    # 定义一个StreamHandler，将 INFO 级别或更高的日志信息打印到标准错误，并将其添加到当前的日志处理对象#
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    fmt = logging.Formatter('[%(asctime)s] %(filename)s [line:%(lineno)d] %(levelname)s %(message)s')
    console.setFormatter(fmt)
    logging.getLogger('').addHandler(console)
    #################################################################################################
    logging.info( ('client v' + gblVersion ).center(40, '-') )

    main()